<script>
    (function(window) {
        function openStyleEditor(MapStoreAPI, config) {
            const layers = config.resourceConfig && config.resourceConfig.map && config.resourceConfig.map.layers;
            // on the page initialization the last layer is the last one on the configuration
            var layer = layers && layers[layers.length - 1];
            if( layer) {
                // layer id is undefined so we are using the structure used by masptore {layerName}__{layerIndex-1}
                layer.id = layer.name + '__' + (layers.length - 1);
                MapStoreAPI.triggerAction({
                    type: 'TOGGLE_CONTROL',
                    control: 'drawer',
                    property: null
                });
                MapStoreAPI.triggerAction({
                    type: 'LAYERS:SELECT_NODE',
                    id: layer.id,
                    nodeType: 'layer',
                    ctrlKey: false
                });
                function editPermissionListener(action) {
                    const perms = action && action.options && action.options.perms || [];
                    const canEditStyle = perms.includes('change_dataset_style');
                    if(canEditStyle) {
                        MapStoreAPI.offAction('UPDATE_NODE', editPermissionListener);
                        MapStoreAPI.triggerAction({
                            type: 'SHOW_SETTINGS',
                            node: layer.id,
                            nodeType: 'layers',
                            options: {
                                opacity: layer.opacity || 1
                            }
                        });
                        MapStoreAPI.triggerAction({
                            type: 'SET_CONTROL_PROPERTY',
                            control: 'layersettings',
                            property: 'activeTab',
                            value: 'style'
                        });
                        MapStoreAPI.triggerAction({
                            type: 'STYLEEDITOR:TOGGLE_STYLE_EDITOR',
                            layer: null,
                            enabled: true
                        });
                    };
                };
                MapStoreAPI.onAction('UPDATE_NODE', editPermissionListener);
            }
        }
        window.onInitMapStoreAPI = function(MapStoreAPI, config) {
            openStyleEditor(MapStoreAPI, config);
        };
    })(window);
</script>
{% include "./map_edit.html" with plugins_config_key=dataset_style_edit" %}
